package mybatis.plugins;

import mybatis.exception.MyBatisException;
import spring.annotations.Component;
import spring.dao.factory.FactoryBean;
import spring.dao.support.SqlSessionDaoSupport;

@Component
public class MapperFactoryBean<T> extends SqlSessionDaoSupport implements FactoryBean<T> {

    private Class<T> mapperInterface;

    public Class<T> getMapperInterface() {
        return mapperInterface;
    }

    @SuppressWarnings("unchecked")
    public void setMapperInterface(String mapperInterface) {
        try {
            this.mapperInterface = (Class<T>) Class.forName(mapperInterface);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new MyBatisException("注册的mapper接口类型无效，mapperInterface = " + mapperInterface, e);
        }
    }

    @Override
    public T getObject() {
        return getSqlSession().getMapper(this.mapperInterface);
    }

    @Override
    public Class<?> getObjectType() {
        return this.mapperInterface;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

}
